package com.loe.ktui.custom

import android.content.Context
import android.util.AttributeSet
import android.util.TypedValue
import android.view.Gravity
import android.view.ViewGroup
import androidx.core.view.children
import com.loe.ktui.*
import com.loe.ktui.util.KtColor
import com.loe.picker.util.PickerBean
import kotlinx.android.synthetic.main.kt_view_form_radio.view.*
import org.json.JSONArray

open class UiFormRadioView(id: String? = null) : UiFrameLayout(id)
{
    override var width: Any? = MATCH_PARENT

    var isInfo: Boolean? = null
    var title: CharSequence? = null
    var notNull: Boolean? = null
    var names: String? = null
    var codes: String? = null

    var textSize: Any? = 15
    var titleColor: Int? = null
    var titleLeft: Any? = null
    var titleLen: Any? = null
    var tailLen: Any? = null

    var onSelect: (KtFormRadioView.(i: Int, bean: PickerBean) -> Unit)? = null
    fun onSelect(onSelect: KtFormRadioView.(i: Int, bean: PickerBean) -> Unit)
    {
        this.onSelect = onSelect
    }

    fun initUI(context: Context, view: KtFormRadioView)
    {
        super.initUI(context, view)

        isInfo?.let { view.isInfo = it }
        title?.let { view.title = it }
        notNull?.let { view.notNull = it }

        textSize?.let { view.setTextSizePx(it.distFloat) }
        titleColor?.let { view.titleColor = it }
        titleLeft?.let { view.titleLeft = it.distFloat }
        titleLen?.let { view.titleLen = it.distFloat }
        tailLen?.let { view.tailLen = it.distFloat }

        onSelect?.let { onSelect -> view.setOnSelectListener { i, bean -> view.onSelect(i, bean) } }
    }

    override fun createView(context: Context, parent: ViewGroup?): KtFormRadioView
    {
        return KtFormRadioView(context).also()
        {
            initUI(context, it)
            addToParent(parent, it)
        }
    }
}

fun Any.ui_FormRadioView(id: String? = null, block: (UiFormRadioView.() -> Unit)? = null): UiFormRadioView
{
    val ui = UiFormRadioView(id)
    block?.let { ui.it() }
    if (this is UiGroup) addChild(ui)
    return ui
}

/** 表单选择View */
class KtFormRadioView : KtFrameLayout
{
    constructor(context: Context) : super(context)
    {
        onCreate(null)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    {
        onCreate(attrs)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
    {
        onCreate(attrs)
    }

    private fun onCreate(attrs: AttributeSet?)
    {
        val root = inflate(context, R.layout.kt_view_form_radio, null)
        addView(root, MATCH_PARENT, MATCH_PARENT)

        attrs?.let()
        {
            val typedArray = context.obtainStyledAttributes(it, R.styleable.KtFormRadioView)

            // title
            title = typedArray.getString(R.styleable.KtFormRadioView_kt_form_title) ?: ""
            // is_info
            isInfo = typedArray.getBoolean(R.styleable.KtFormRadioView_kt_form_isInfo, false)
            // not_null
            notNull = typedArray.getBoolean(R.styleable.KtFormRadioView_kt_form_notNull, false)

            // size
            textSize = dp(typedArray.getDimension(R.styleable.KtFormRadioView_kt_form_textSize, ktPx(15).toFloat()))
            // title_color
            titleColor = typedArray.getColor(R.styleable.KtFormRadioView_kt_form_titleColor, KtColor.grayDeep)
            // titleLeft
            titleLeft = typedArray.getDimension(R.styleable.KtFormRadioView_kt_form_titleLeft, ktPx(15).toFloat())
            // titleLen
            titleLen = typedArray.getDimension(R.styleable.KtFormRadioView_kt_form_titleLen, ktPx(92).toFloat())
            // tailLen
            tailLen = typedArray.getDimension(R.styleable.KtFormRadioView_kt_form_tailLen, ktPx(6).toFloat())

            // list
            val names = typedArray.getString(R.styleable.KtFormRadioView_kt_form_names) ?: ""
            val codes = typedArray.getString(R.styleable.KtFormRadioView_kt_form_codes) ?: ""
            setData(names.split(","), codes.split(","))

            // select
            val select = typedArray.getInt(R.styleable.KtFormRadioView_kt_form_select, -1)
            select(select)

            typedArray.recycle()
        }

        if (minimumHeight > 0)
        {
            root.minimumHeight = minimumHeight
        }
    }

    var isInfo = false

    var index = -1
        private set

    var list = ArrayList<PickerBean>()

    var bean: PickerBean? = null
        private set

    val name get() = bean?.name ?: ""
    val code get() = bean?.code ?: ""

    fun setData(mList: List<PickerBean>)
    {
        list.clear()
        list.addAll(mList)

        viewRadios.removeAllViews()
        index = -1
        bean = null
        ui_FlexLayout()
        {
            paddingLeft = dp(titleLen)
            paddingRight = dp(tailLen)
            paddingV = 5
            list.forEachIndexed()
            { i, bean ->
                ui_Text()
                {
                    height = 40
                    width = WRAP_CONTENT
                    gravity = Gravity.CENTER_VERTICAL
                    paddingLeft = 15
                    paddingRight = 10
                    text = bean.name
                    textSize = 15
                    imageRes = R.mipmap.kt_icon_radio_0
                    if (isInfo) imageColor = KtColor.gray
                    imageHeight = 20
                    imageWidth = 20
                    imagePadding = 9

                    onClick()
                    {
                        if (!isInfo) select(i)
                    }
                }
            }
        }.initUI(context, viewRadios)
    }

    fun setData(nameList: List<String>, codeList: List<String>)
    {
        val mList = ArrayList<PickerBean>()
        nameList.forEachIndexed()
        { i, name ->
            val code = if (i < codeList.size) codeList[i] else name
            mList.add(PickerBean(code, name))
        }
        setData(mList)
    }

    fun setData(js: JSONArray, nameKey: String = PickerBean.NAME_KEY, codeKey: String = PickerBean.CODE_KEY)
    {
        if (js.length() == 0) return
        val mList = ArrayList<PickerBean>()
        for (i in 0 until js.length())
        {
            val json = js.optJSONObject(i)
            val name = json.optString(nameKey)
            val code = json.optString(codeKey).ifEmpty { name }
            mList.add(PickerBean(code, name))
        }
        setData(mList)
//        titleLen = titleLen
    }

    var notNull = true
        set(value)
        {
            field = value
            textNotNull.visibility = if (value && title.isNotEmpty()) VISIBLE else INVISIBLE
        }

    var title: CharSequence
        get() = textTitle.text
        set(value)
        {
            textTitle.text = value
            notNull = notNull
        }

    fun select(i: Int, isListener: Boolean = true)
    {
        if (i < 0 || i >= viewRadios.childCount) return
        index = i
        if (i < list.size)
        {
            bean = list[i]
        }
        viewRadios.children.forEachIndexed()
        { index, view ->
            view as KtTextView
            if (i == index)
            {
                view.imageRes = R.mipmap.kt_icon_radio_1
            } else
            {
                view.imageRes = R.mipmap.kt_icon_radio_0
            }
            view.notifyImage()
        }
        if (isListener && bean != null) onSelectListener?.invoke(i, bean!!)
    }

    fun selectName(name: String, isListener: Boolean = true)
    {
        select(list.indexOfFirst { it.name == name }, isListener)
    }

    fun selectCode(code: String, isListener: Boolean = true)
    {
        select(list.indexOfFirst { it.code == code }, isListener)
    }

    var titleColor = KtColor.gray
        set(value)
        {
            field = value
            textTitle.setTextColor(value)
        }

    var textSize = 0f
        set(value)
        {
            field = value
            textTitle.textSize = textSize
        }

    var titleLeft = 0f
        set(value)
        {
            field = value
            textTitle.marginLeftPx = value.toInt()
        }

    var titleLen = 0f
        set(value)
        {
            field = value
            viewRadios.setPadding(value.toInt(), ktPx(5), tailLen.toInt(), ktPx(5))
        }

    var tailLen = 0f
        set(value)
        {
            field = value
            viewRadios.setPadding(titleLen.toInt(), ktPx(5), value.toInt(), ktPx(5))
        }

    fun setTextSizePx(px: Float)
    {
        textTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, px)
    }

    fun isEmpty(): Boolean = index < 0

    private var onSelectListener: ((i: Int, bean: PickerBean) -> Unit)? = null

    fun setOnSelectListener(listener: (i: Int, bean: PickerBean) -> Unit)
    {
        this.onSelectListener = listener
    }

    private fun dp(pxValue: Float): Float
    {
        val scale = resources.displayMetrics.density
        return (pxValue + 0.5f) / scale
    }
}